package com.dfd.security.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.annotation.Resource;

/*
 *文件名: SecrityConfig
 *创建者: 东东
 *创建时间:2021/9/2 13:22
 *描述:   WebSecurityConfigurerAdapter是Spring提供的对安全配置的适配器
 *          使用@EnableWebSecurity来开启Web安全
 */
@Configuration
@EnableWebSecurity
public class SecrityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private SecrityProperties secrityProperties;

    @Resource
    @Qualifier("loginAuthenticationFailureHandler")
    private AuthenticationFailureHandler loginAuthenticationFailureHandler;
    @Resource
    @Qualifier("loginAuthenticationSuccessHandler")
    private AuthenticationSuccessHandler loginAuthenticationSuccessHandler;

    /**
     * 重写此方法，来定义自己的需求
     *  允许basic登录
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin() //允许表单登录
                .loginPage("/authencation/require")
                //使用/authentication/form的url来处理表单登录请求
                .loginProcessingUrl("/authentication/form")
                //添加自定义登录成功处理器
                .successHandler(loginAuthenticationSuccessHandler)
                //添加自定义登录失败处理器
                .failureHandler(loginAuthenticationFailureHandler)
                .and()
                .authorizeRequests() //对请求进行授权
                //对/authencation/require以及配置页请求放行
                .antMatchers("/authencation/require",
                        secrityProperties.getBrowser().getLoginPage())
                .permitAll()
                .anyRequest()  //任何请求
                .authenticated()   //都需要身份认证
                .and()
                .csrf().disable(); //关闭跨站请求伪造防护
    }

    /*
     * 添加一个加密工具对bean,PasswordEncoder为接口
     * BCryptPasswordEncoder为实现类，也可以用其他加密实现类代替
     * 如MD5等
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
